package com.ruoyi.system.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.system.domain.DrugUpload;
import com.ruoyi.system.service.IDrugUploadService;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 药品病历文件上传Controller
 * 
 * @author wmb
 * @date 2021-03-01
 */
@RestController
@RequestMapping("/drugUpload")
public class DrugUploadController extends BaseController
{

    private static final Logger LOGGER = LoggerFactory.getLogger(DrugUploadController.class);
    @Autowired
    private IDrugUploadService drugUploadService;
    @Value("${minio.url}")
    private String MINIO_URL;

    @Value("${minio.endpoint}")
    private String ENDPOINT;

    @Value("${minio.bucketname}")
    private String BUCKET_NAME;

    @Value("${minio.accessKey}")
    private String ACCESS_KEY;

    @Value("${minio.secretKey}")
    private String SECRET_KEY;
    /**
     * 查询药品病历文件上传列表
     */
    @PreAuthorize("@ss.hasPermi('system:upload:list')")
    @GetMapping("/list")
    public TableDataInfo list(DrugUpload drugUpload)
    {
        startPage();
        List<DrugUpload> list = drugUploadService.selectDrugUploadList(drugUpload);
        return getDataTable(list);
    }

    /**
     * 导出药品病历文件上传列表
     */
    @PreAuthorize("@ss.hasPermi('system:upload:export')")
    @Log(title = "药品病历文件上传", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DrugUpload drugUpload) throws IOException
    {
        List<DrugUpload> list = drugUploadService.selectDrugUploadList(drugUpload);
        ExcelUtil<DrugUpload> util = new ExcelUtil<DrugUpload>(DrugUpload.class);
        util.exportExcel(response, list, "upload");
    }

    /**
     * 获取药品病历文件上传详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:upload:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(drugUploadService.selectDrugUploadById(id));
    }

    /**
     * 新增药品病历文件上传
     */
    @PreAuthorize("@ss.hasPermi('system:upload:add')")
    @Log(title = "药品病历文件上传", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DrugUpload drugUpload)
    {
        return toAjax(drugUploadService.insertDrugUpload(drugUpload));
    }

    /**
     * 修改药品病历文件上传
     */
    @PreAuthorize("@ss.hasPermi('system:upload:edit')")
    @Log(title = "药品病历文件上传", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DrugUpload drugUpload)
    {
        return toAjax(drugUploadService.updateDrugUpload(drugUpload));
    }

    /**
     * 删除药品病历文件上传
     */
    @PreAuthorize("@ss.hasPermi('system:upload:remove')")
    @Log(title = "药品病历文件上传", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(drugUploadService.deleteDrugUploadByIds(ids));
    }



    @Log(title = "上传病历", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:upload:add')")
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, boolean updateSupport, HttpServletRequest request) throws Exception
    {

        try {

            MinioClient minioClient = new MinioClient(ENDPOINT,ACCESS_KEY,SECRET_KEY);
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if(isExist){
                LOGGER.info("存储桶已经存在");
            }else {
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME,"*.*", PolicyType.READ_ONLY);
            }
            String filename = file.getOriginalFilename();
            //String filename = DateUtils.dateTimeNow()+"东方融创.zip";
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            String objectName = "ai"+"/"+dateTimeFormatter.format(LocalDate.now())+"/"+filename;
            minioClient.putObject(BUCKET_NAME,objectName,file.getInputStream(),file.getContentType());
            LOGGER.info("上传成功");
            // Map<String,String> map = new HashMap<>(8);
            // map.put("url",MINIO_URL+"/"+BUCKET_NAME+"/"+BUCKET_NAME+"/"+objectName);

            DrugUpload drugUpload = new DrugUpload();
            //drugUpload.setCode(result.getCode());
            //drugUpload.setMessage(result.getMessage());
            drugUpload.setName(filename);
            drugUpload.setMessage(objectName);
            drugUpload.setPath(URLDecoder.decode(minioClient.getObjectUrl(BUCKET_NAME, objectName),"UTF-8"));
            drugUploadService.insertDrugUpload(drugUpload);
            return AjaxResult.success("上传成功");

        } catch (Exception e) {
            LOGGER.info("上传发生错误:{}!",e.getMessage());
        }
        return AjaxResult.success("上传失败");
    }


    @Log(title = "处理病历", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:upload:add')")
    @PostMapping("/handleDrug")
    public AjaxResult handleDrug(@RequestParam("uploadId") Long uploadId){
        drugUploadService.handleDrug(uploadId);
        return AjaxResult.success("处理成功");
    }
}
